//
//  IndentViewController.m
//  cm
//
//  Created by suyibaishan on 2017/11/4.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "IndentViewController.h"
#import "IndentCell.h"

@interface IndentViewController () <UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    UIView *footView;
    UILabel *remarkLabel;
    UITextField *remarkField;
    UIButton *submitBtn;
    UIView *settleView;
    UILabel *settleLabel;
    NSInteger quantity;
    CGFloat totalAmount;
}
@end

@implementation IndentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createIndentView];
}

-(void)createIndentView
{
    self.titleLabel.text = @"确认订单";
    self.backButton.hidden = NO;
    self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.baseBarHeight+10, kScreenWidth, kScreenHeight - self.baseBarHeight-59) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [self.view addSubview:_tableView];
    
    [self createfootView];
    _tableView.tableFooterView = footView;
    
    [self createSettleView];
}

-(UIView *)createSettleView
{
    settleView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49)];
    settleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:settleView];
    
//    UIView *line = [[UIView alloc] init];
//    line.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
//    [settleView addSubview:line];
//    line.sd_layout
//    .topSpaceToView(settleView, 0)
//    .leftSpaceToView(settleView, 0)
//    .widthIs(kScreenWidth)
//    .heightIs(0.5);
    
    submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(kScreenWidth - 100, 0, 100, 49);
    [submitBtn setTitle:@"提交订单" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    submitBtn.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [submitBtn addTarget:self action:@selector(submitBtnHanlder) forControlEvents:UIControlEventTouchUpInside];
    [settleView addSubview:submitBtn];
    
    quantity = 0;
    totalAmount = 0.0;
    for (NSDictionary *dict in self.dataSource) {
        quantity = quantity + [dict[@"quantity"] integerValue];
        totalAmount = totalAmount + [dict[@"downPayment"] floatValue]*[dict[@"quantity"] integerValue];
    }
    
    settleLabel = [[UILabel alloc] init];
//    settleLabel.text = @"共2件合计首付：¥213456.00";
    settleLabel.font = [UIFont systemFontOfSize:14];
    settleLabel.textAlignment = NSTextAlignmentRight;
    settleLabel.textColor = [UIColor blackColor];
    [settleView addSubview:settleLabel];
    settleLabel.sd_layout
    .topSpaceToView(settleView, 0)
    .rightSpaceToView(submitBtn, 10)
    .widthIs(kScreenWidth - 120)
    .heightIs(49);
    NSMutableAttributedString *settleStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"共%ld件合计首付：¥%.2f",quantity,totalAmount]];
    [settleStr addAttribute:NSForegroundColorAttributeName
                      value:[UIColor colorWithRed:0.99 green:0.33 blue:0.16 alpha:1]
                      range:NSMakeRange(1, 1)];
    [settleStr addAttribute:NSForegroundColorAttributeName
                      value:[UIColor colorWithRed:0.99 green:0.33 blue:0.16 alpha:1]
                      range:NSMakeRange(8, settleStr.length - 8)];
    settleLabel.attributedText = settleStr;
    
    return settleView;
}

-(void)submitBtnHanlder
{
    NSMutableArray *itemArr = [NSMutableArray array];
    for (NSDictionary *dict in self.dataSource) {
        [itemArr addObject:dict[@"id"]];
    }
    [[ToolNet sharedManager] createItemOrder:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] itemIds:[itemArr componentsJoinedByString:@","] orderAmount:totalAmount remark:remarkField.text url:MCreateItemOrder completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            [self.navigationController popToRootViewControllerAnimated:NO];
            [TSMessage showMessage:@"下单成功" type:TSMessageNotificationTypeSuccess];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWHOMEVIEW" object:nil];
            });
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
    }];
}

-(void)createfootView
{
    footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    footView.backgroundColor = [UIColor whiteColor];
        
    remarkLabel = [[UILabel alloc] init];
    remarkLabel.numberOfLines = 2;
    remarkLabel.text = @"买家留言：";
    remarkLabel.textColor = [UIColor blackColor];
    remarkLabel.font = [UIFont systemFontOfSize:13];
    [footView addSubview:remarkLabel];
    remarkLabel.sd_layout
    .leftSpaceToView(footView, 10)
    .topSpaceToView(footView, 5)
    .widthIs(70)
    .heightIs(35);
    
    remarkField = [[UITextField alloc] init];
    remarkField.placeholder = @"选填(建议填写对本次交易的备注)";
    remarkField.returnKeyType = UIReturnKeyDone;
    remarkField.font = [UIFont systemFontOfSize:13];
    [footView addSubview:remarkField];
    remarkField.sd_layout
    .leftSpaceToView(remarkLabel, 0)
    .topSpaceToView(footView, 5)
    .widthIs(kScreenWidth - 95)
    .heightIs(35);
    
    UIView *grayView = [[UIView alloc] init];
    grayView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [footView addSubview:grayView];
    grayView.sd_layout
    .leftSpaceToView(footView, 0)
    .topSpaceToView(footView, 45)
    .widthIs(kScreenWidth)
    .heightIs(35);

    UILabel *remindLabel = [[UILabel alloc] init];
    remindLabel.textAlignment = NSTextAlignmentRight;
    remindLabel.text = @"*订单成功后优先扣除购车基金";
    remindLabel.textColor = [UIColor colorWithRed:0.99 green:0.33 blue:0.16 alpha:1];
    remindLabel.font = [UIFont systemFontOfSize:12];
    [grayView addSubview:remindLabel];
    remindLabel.sd_layout
    .rightSpaceToView(grayView, 10)
    .topSpaceToView(grayView, 5)
    .widthIs(kScreenWidth - 100)
    .heightIs(25);
}

#pragma - UITableViewDataSource,UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier =  @"indentifier";
    IndentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[IndentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = [[IndentModel alloc] initWithDictionary:self.dataSource[indexPath.row]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
